package com.shopping_back.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shopping_back.mapper.UserAccountMapper;
import com.shopping_back.pojo.dto.UserInfoDTO;
import com.shopping_back.pojo.entity.UserAccount;
import com.shopping_back.pojo.entity.UserProfile;
import com.shopping_back.mapper.UserProfileMapper;
import com.shopping_back.service.IUserProfileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <p>
 * 用户档案表 服务实现类
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@Service
@RequiredArgsConstructor
public class UserProfileServiceImpl extends ServiceImpl<UserProfileMapper, UserProfile> implements IUserProfileService {

    private final UserAccountMapper userAccountMapper;

    private final UserProfileMapper userProfileMapper;

    @Override
    public UserInfoDTO getUserInfo(Long userId) {
        // 打印查询的userId，用于核对
        System.out.println("查询的userId：" + userId);

        UserAccount userAccount = userAccountMapper.selectById(userId);
        UserProfile userProfile = userProfileMapper.selectById(userId);

        if (userAccount == null) {
            // 打印错误信息，提示实际查询的userId
            throw new RuntimeException("用户不存在，查询的userId：" + userId);
        }
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        BeanUtils.copyProperties(userAccount, userInfoDTO);
        if (userProfile != null) {
            BeanUtils.copyProperties(userProfile, userInfoDTO, "userId");
            userInfoDTO.setAvatarUrl(userProfile.getAvatarUrl());
            userInfoDTO.setAddress(userProfile.getAddress());
        }
        return userInfoDTO;
    }

    @Override
    @Transactional
    public void updateUserInfo(UserInfoDTO userInfoDTO) {
        // 更新 user_account 表
        UserAccount userAccount = new UserAccount();
        userAccount.setId(userInfoDTO.getId());
        userAccount.setMobile(userInfoDTO.getMobile());
        userAccount.setEmail(userInfoDTO.getEmail());
        userAccountMapper.updateById(userAccount);

        // 更新 user_profile 表
        UserProfile userProfile = new UserProfile();
        userProfile.setUserId(userInfoDTO.getId());
        userProfile.setRealName(userInfoDTO.getRealName());
        userProfile.setGender(userInfoDTO.getGender());
        userProfile.setBirthday(userInfoDTO.getBirthday());
        userProfile.setAvatarUrl(userInfoDTO.getAvatarUrl());
        userProfile.setAddress(userInfoDTO.getAddress());

        LambdaQueryWrapper<UserProfile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserProfile::getUserId, userInfoDTO.getId());
        if (userProfileMapper.exists(queryWrapper)) {
            userProfileMapper.updateById(userProfile);
        } else {
            userProfileMapper.insert(userProfile);
        }
    }

    @Override
    @Transactional
    public UserProfile exchangePoints(Long userId, Integer points, Integer wallet) {
        // 1. 参数校验
        if (userId == null || points == null || wallet == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (points <= 0 || wallet <= 0) {
            throw new IllegalArgumentException("积分和金额必须大于0");
        }

        // 2. 查询用户账户
        UserProfile profile = userProfileMapper.selectById(userId);
        if (profile == null) {
            throw new RuntimeException("用户账户不存在");
        }

        // 3. 验证积分是否足够
        if (profile.getPoints() < points) {
            throw new RuntimeException("积分不足，当前积分：" + profile.getPoints());
        }

        // 4. 执行兑换
        profile.setPoints(profile.getPoints() - points);
        profile.setWallet(profile.getWallet() + wallet);
        userProfileMapper.updateById(profile);

        // 5. 返回更新后的用户档案
        return this.getByUserId(userId);
    }

    @Override
    public UserProfile getByUserId(Long userId) {
        return getOne(new LambdaQueryWrapper<UserProfile>()
                .eq(UserProfile::getUserId, userId));
    }

    @Override
    @Transactional
    public UserProfile getMember(Long userId){
        // 1. 基础校验
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        // 2. 查询数据库
        UserProfile profile = userProfileMapper.selectById(userId);
        if (profile == null) {
            throw new RuntimeException("用户不存在");
        }
        return profile;
    }

    // 会员等级积分倍率
    private static final Map<Integer, Double> MEMBER_RATES = Map.of(
            1, 0.0,   // 银米
            2, 1.0,   // 金米
            3, 1.5,   // 白金
            4, 2.0,   // 钻石
            5, 3.0    // 至尊
    );

    public int getMembershipLevel(Long userId) {
        UserProfile profile = this.getOne(
                new LambdaQueryWrapper<UserProfile>()
                        .eq(UserProfile::getUserId, userId)
                        .select(UserProfile::getMembershipLevel) // 只查询会员等级字段
        );
        return profile != null ? profile.getMembershipLevel() : null;
    }


    public int addPoints(Long userId, int points) {
        // 更新用户总积分
        int updated = userProfileMapper.selectById(userId).getPoints() + points;
        userProfileMapper.updateById(userProfileMapper.selectById(userId).setPoints(updated));
        return updated;
    }
}
